package com.longcai.service.impl.clyjuser;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.auth.SysShopsRoleUser;
import com.longcai.entity.auth.vo.SysclyjuserVo;
import com.longcai.entity.customer.ClyjUser;
import com.longcai.mapper.SysShopsRoleUserMapper;
import com.longcai.mapper.clyjuser.ClyjUserMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.clyjuser.ClyjUserService;
import com.longcai.util.LoginUser;
import com.longcai.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-03-31
 */
@Service
public class ClyjUserServiceImpl extends ServiceImpl<ClyjUserMapper, ClyjUser> implements ClyjUserService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjUserMapper clyjUserMapper;
    @Autowired
    private SysShopsRoleUserMapper sysShopsRoleUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 根据名称查询用户信息
     *
     * @param name
     * @return
     */
    @Override
    public ClyjUser getName(String name) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", name);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询{}", clyjUser);
            return clyjUser;
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 修改密码
     *
     * @param clyjUser
     * @param newPassword
     * @return
     */
    @Override
    public ApiResult<ClyjUser> updatePassword(ClyjUser clyjUser, String newPassword) {
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", clyjUser.getUsername());

        ClyjUser clyjUser1 = this.clyjUserMapper.selectOne(queryWrapper);
        if (clyjUser1 == null) {
            return ApiResult.fail("密码错误");
        }
        //旧密码比较
        boolean matches = passwordEncoder.matches(clyjUser.getPassword(), clyjUser1.getPassword());
        if (!matches) {
            return ApiResult.fail("输入旧密码错误");
        }
        clyjUser1.setPassword(passwordEncoder.encode(newPassword));
        clyjUserMapper.updateById(clyjUser1);
        return ApiResult.success();
    }

    /**
     * 查看用户信息
     *
     * @return
     */
    @Override
    public ClyjUser getuser() {
        //查询登录用户角色
        LoginUser loginUser = UserUtil.getLoginUser();
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", loginUser.getUserId());
            queryWrapper.eq("ismich", "1");
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询成功");
            return clyjUser;
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            e.getMessage();
        }
        return null;
    }

    /**
     * 查询所有用户名
     *
     * @param username
     * @return
     */
    @Override
    public ClyjUser getUser(String username) {
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.clyjUserMapper.selectOne(queryWrapper);
    }

    @Override
    public List<ClyjUser> getusername() {
        return clyjUserMapper.getusername();
    }

    /**
     * 获取会员列表
     *
     * @param clyjUser
     * @param pageHelper
     * @return
     */
    @Override
    public PageTableResponse userList(ClyjUser clyjUser, PageHelper pageHelper) {
        //分页
        Page<ClyjUser> page = new Page<ClyjUser>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(clyjUser.getUsername())) {
            queryWrapper.like("username", clyjUser.getUsername());
        }
        if (!StringUtils.isEmpty(clyjUser.getPhone())) {
            queryWrapper.like("phone", clyjUser.getPhone());
        }
        IPage<ClyjUser> sysRoleIPage = this.clyjUserMapper.selectPage(page, queryWrapper);
        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
        return pageTableResponse;
    }

    /**
     * 开通导购会员列表
     *
     * @param clyjUser
     * @param pageHelper
     * @return
     */
    @Override
    public PageTableResponse userLists(ClyjUser clyjUser, PageHelper pageHelper) {
        //分页
        Page<ClyjUser> page = new Page<ClyjUser>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(clyjUser.getPhone())) {
            queryWrapper.like("phone", clyjUser.getPhone());
        }
        queryWrapper.eq("level", 0);
        IPage<ClyjUser> sysRoleIPage = this.clyjUserMapper.selectPage(page, queryWrapper);
        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
        return pageTableResponse;
    }

    /**
     * 根据id获取会员信息
     *
     * @param id
     * @return
     */
    @Override
    public ApiResult getById(String id) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", id);
            ClyjUser clyjUser = this.clyjUserMapper.selectOne(queryWrapper);
            logger.debug("查询成功++++++++++", clyjUser);
            return ApiResult.success(clyjUser);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败" + e.getMessage());
        }
    }

    /**
     * 修改会员信息
     *
     * @param clyjUser
     * @return
     */
    @Override
    public Integer updateUser(SysclyjuserVo clyjUser) {
        try {
            Integer integer = this.clyjUserMapper.updateById(clyjUser);
            saveSysUserRoles(clyjUser.getUserId(), clyjUser.getRoleId());
            logger.debug("修改成功++++++++++", integer);
            return integer;
        } catch (Exception e) {
            logger.error("修改失败+++++");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delClyjUser(String id) {
        try {
            this.clyjUserMapper.deleteById(id);
            logger.debug("删除成功+++++++++", id);
        } catch (Exception e) {
            logger.error("删除失败+++++++++++", id);
            e.printStackTrace();
        }
    }


    /**
     * 添加角色中间表
     *
     * @param userId
     * @param roleId
     */
    private void saveSysUserRoles(String userId, String roleId) {
        if (roleId != null) {
            sysShopsRoleUserMapper.deleteById(userId);
            if (roleId != null) {
                SysShopsRoleUser sysShopsRoleUser = new SysShopsRoleUser(userId, roleId);
                sysShopsRoleUserMapper.insert(sysShopsRoleUser);
            }
        }
    }

    /**
     * 忘记密码（修改密码）
     *
     * @param phone
     * @param password
     * @return
     * @paramcode
     */
    @Override
    public ApiResult updatePwd(String phone, String password) {
        try {
            QueryWrapper<ClyjUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            ClyjUser user = this.clyjUserMapper.selectOne(queryWrapper);
            user.setPassword(passwordEncoder.encode(password));
            Integer integer = clyjUserMapper.updateById(user);
            logger.debug("修改成功");
            return ApiResult.success(integer);
        } catch (Exception e) {
            logger.error("修改失败");
            e.printStackTrace();
            return ApiResult.fail("修改失败" + e.getMessage());
        }
    }
}
